<!DOCTYPE html>
<html>
  <body>
    <button id="computeBtn">运行计算</button>
    <button id="runParallel">运行runParallel</button>
    <div id="result"></div>

    <script type="module">
      import { add } from "./build/release.js";
      import { runParallel } from "./main.js";
      import "./wasm-worker.js";

      document
        .getElementById("runParallel")
        .addEventListener("click", async () => {
          runParallel();
        });

      async function loadWasm() {
        // 初始化内存(共享内存)
        const memory = new WebAssembly.Memory({ initial: 10 });
        // 加载Wasm模块
        const { instance } = await WebAssembly.instantiateStreaming(
          fetch("./build/release.wasm"),
          {
            env: { memory },
            Math, // 提供Math函数(如Math.sqrt)
          }
        );

        return instance.exports;
      }

      // 使用示例
      document
        .getElementById("computeBtn")
        .addEventListener("click", async () => {
          const wasm = await loadWasm();
          const output = document.getElementById("result");

          // 1. 简单计算测试
          output.innerHTML = "计算中...";

          setTimeout(() => {
            // 让UI有机会更新
            const start = performance.now();
            const sum = wasm.compute(10000000);
            const time = performance.now() - start;

            output.innerHTML = `
          <p>平方和计算结果: ${sum}</p>
          <p>耗时: ${time.toFixed(2)}ms</p>
          <p>add(1, 2) = ${add(1, 2)}</p>
        `;
          }, 50);
        });
    </script>
  </body>
</html>
